import { Database, Project } from '@/types/domain_models'
import { Dependency, PomOptions } from '@/types/pom'
import TianzhiJavaGenerator from '.'
import { XMLBuilder } from 'fast-xml-parser'

const databaseDependencies: { [key: string]: Dependency } = {
  mysql: {
    groupId: 'mysql',
    artifactId: 'mysql-connector-java',
    scope: 'runtime',
  },
  oracle: {
    groupId: 'com.oracle',
    artifactId: 'ojdbc6',
    version: '11.2.0.1.0',
  },
}

/**
 * 最基础的 SpringBoot POM 文件配置
 */
const BASE_POM: Partial<PomOptions> = {
  modelVersion: '4.0.0',
  parent: {
    groupId: 'org.springframework.boot',
    artifactId: 'spring-boot-starter-parent',
    version: '2.6.6',
    relativePath: '',
  },
  dependencies: [
    {
      dependency: {
        groupId: 'org.springframework.boot',
        artifactId: 'spring-boot-starter-web',
      },
    },
    {
      dependency: {
        groupId: 'org.mybatis.spring.boot',
        artifactId: 'mybatis-spring-boot-starter',
        version: '2.2.2',
      },
    },
    {
      dependency: {
        groupId: 'com.baomidou',
        artifactId: 'mybatis-plus-boot-starter',
        version: '3.5.1',
      },
    },
    {
      dependency: {
        groupId: 'org.projectlombok',
        artifactId: 'lombok',
        optional: true,
      },
    },
    {
      dependency: {
        groupId: 'org.springframework.boot',
        artifactId: 'spring-boot-starter-test',
        scope: 'test',
      },
    },
  ],
  build: {
    plugins: [
      {
        plugin: {
          groupId: 'org.springframework.boot',
          artifactId: 'spring-boot-maven-plugin',
          configuration: {
            excludes: [
              {
                exclude: {
                  groupId: 'org.projectlombok',
                  artifactId: 'lombok',
                },
              },
            ],
          },
        },
      },
    ],
  },
}

/**
 * 写入 POM 文件
 */
export function writing(generator: TianzhiJavaGenerator, database: Database, project: Project) {
  const pom: Partial<PomOptions> = {
    ...BASE_POM,
    groupId: project.packageName,
    artifactId: project.name,
    name: project.name,
    description: project.desc,
    version: project.version,
  }

  const databaseType = database.type
  const databaseDependency = databaseDependencies[databaseType]
  pom.dependencies.push({ dependency: databaseDependency })

  const xml = `
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    ${new XMLBuilder({}).build(pom)}
</project>`
  generator.fs.write(generator.destinationPath('pom.xml'), xml)
}
